<!DOCTYPE html>
<html lang="zh">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Python可视化 | ChenDong Zhu&#39;s Blog</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noodp" />
<meta name="Description" content="关于Python可视化的笔记"><link rel="prev" href="/2020/01/%E7%BB%9F%E8%AE%A1%E5%AD%A6%E4%B9%A0%E6%96%B9%E6%B3%95/" /><link rel="next" href="/2020/12/%E5%A4%87%E6%88%98%E7%BE%8E%E8%B5%9B/" /><link rel="canonical" href="/2020/01/python%E5%8F%AF%E8%A7%86%E5%8C%96/" />
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="theme-color" content="#ffffff"><meta property="og:title" content="Python可视化" />
<meta property="og:description" content="关于Python可视化的笔记" />
<meta property="og:type" content="article" />
<meta property="og:url" content="/2020/01/python%E5%8F%AF%E8%A7%86%E5%8C%96/" />
<meta property="article:published_time" content="2020-01-01T09:00:00+08:00" />
<meta property="article:modified_time" content="2020-01-01T09:00:00+08:00" />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Python可视化"/>
<meta name="twitter:description" content="关于Python可视化的笔记"/>
<script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "Python可视化",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "\/2020\/01\/python%E5%8F%AF%E8%A7%86%E5%8C%96\/"
        },"image": {
                "@type": "ImageObject",
                "url": "\/cover.png",
                "width":  800 ,
                "height":  600 
            },"genre": "posts","keywords": "Python, matplotlib","wordcount":  1994 ,
        "url": "\/2020\/01\/python%E5%8F%AF%E8%A7%86%E5%8C%96\/","datePublished": "2020-01-01T09:00:00\u002b08:00","dateModified": "2020-01-01T09:00:00\u002b08:00","license": "This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.","publisher": {
                "@type": "Organization",
                "name": "xxxx",
                "logo": {
                "@type": "ImageObject",
                "url": "\/logo.png",
                "width":  127 ,
                "height":  40 
                }
            },"description": "关于Python可视化的笔记"
    }
    </script><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="/css/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/css/lib/animate/animate.min.css"></head>
    <body><script>
            window.isDark = (window.localStorage && window.localStorage.getItem('theme')) === 'dark';
            window.isDark && document.body.classList.add('dark-theme');
        </script><div class="wrapper"><nav class="navbar">
    <div class="navbar-container">
        <div class="navbar-header animated bounceIn">
            <a href="/">ChenDong Zhu&#39;s Blog</a>
        </div>
        <div class="navbar-menu"><a class="menu-item" href="/posts" title="">文章</a><a class="menu-item" href="/tags" title="">标签</a><a class="menu-item" href="/categories" title="">分类</a><a class="menu-item" href="/about" title="">关于</a><a class="menu-item" href="https://hugo-loveit-en.netlify.com" title="English"><i class="fas fa-language fa-fw"></i></a><a href="javascript:void(0);" class="theme-switch"><i class="fas fa-adjust fa-rotate-180 fa-fw" title="切换主题"></i></a>
        </div>
    </div>
</nav><nav class="navbar-mobile">
    <div class="navbar-container">
        <div class="navbar-header">
            <div class="navbar-header-title animated bounceIn">
                <a href="/">ChenDong Zhu&#39;s Blog</a>
            </div>
            <div class="menu-toggle" id="menu-toggle">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="navbar-menu" id="mobile-menu"><a class="menu-item" href="/posts" title="">文章</a><a class="menu-item" href="/tags" title="">标签</a><a class="menu-item" href="/categories" title="">分类</a><a class="menu-item" href="/about" title="">关于</a><a class="menu-item" href="https://hugo-loveit-en.netlify.com" title="English"></a><a href="javascript:void(0);" class="theme-switch"><i class="fas fa-adjust fa-rotate-180 fa-fw" title="切换主题"></i></a>
        </div>
    </div>
</nav><main class="main">
                <div class="container"><article class="page"><h1 class="post-title animated flipInX">Python可视化</h1><div class="post-meta">
            <div class="post-meta-main"><a class="author" href="/" rel="author" target="_blank">
                    <i class="fas fa-user-circle fa-fw"></i>ChenDong Zhu
                </a>&nbsp;<span class="post-category">收录于&nbsp;<i class="far fa-folder fa-fw"></i><a href="/categories/%E5%AD%A6%E4%B9%A0/">学习</a>&nbsp;</span></div>
            <div class="post-meta-other"><i class="far fa-calendar-alt fa-fw"></i><time datetime=2020-01-01>2020-01-01</time>&nbsp;
                <i class="fas fa-pencil-alt fa-fw"></i>约 1994 字&nbsp;
                <i class="far fa-clock fa-fw"></i>预计阅读 4 分钟&nbsp;</div>
        </div><div class="post-toc" id="post-toc">
                <h2 class="post-toc-title">目录</h2>
                <div class="post-toc-content"><nav id="TableOfContents">
  <ul>
    <li>
      <ul>
        <li><a href="#python-matplotlib">Python matplotlib</a>
          <ul>
            <li><a href="#marplotlib的总体概念">marplotlib的总体概念</a></li>
            <li><a href="#plot函数的使用">plot函数的使用</a></li>
            <li><a href="#分层设色地形图等高线图相关">分层设色地形图/等高线图相关</a>
              <ul>
                <li><a href="#需要用到的函数">需要用到的函数</a></li>
                <li><a href="#在等高线上绘制值">在等高线上绘制值</a></li>
                <li><a href="#绘制直方图">绘制直方图</a></li>
              </ul>
            </li>
          </ul>
        </li>
        <li><a href="#参考文献">参考文献</a></li>
      </ul>
    </li>
  </ul>
</nav></div>
            </div>
            <div class="post-toc-mobile" id="post-toc-mobile">
                <details>
                    <summary>
                        <div class="post-toc-title">
                            <span>目录</span>
                            <span><i class="details icon fas fa-angle-down"></i></span>
                        </div>
                    </summary>
                    <div class="post-toc-content"><nav id="TableOfContentsMobile">
  <ul>
    <li>
      <ul>
        <li><a href="#python-matplotlib">Python matplotlib</a>
          <ul>
            <li><a href="#marplotlib的总体概念">marplotlib的总体概念</a></li>
            <li><a href="#plot函数的使用">plot函数的使用</a></li>
            <li><a href="#分层设色地形图等高线图相关">分层设色地形图/等高线图相关</a>
              <ul>
                <li><a href="#需要用到的函数">需要用到的函数</a></li>
                <li><a href="#在等高线上绘制值">在等高线上绘制值</a></li>
                <li><a href="#绘制直方图">绘制直方图</a></li>
              </ul>
            </li>
          </ul>
        </li>
        <li><a href="#参考文献">参考文献</a></li>
      </ul>
    </li>
  </ul>
</nav></div>
                </details>
            </div><div class="post-content"><p>此笔记记载通过使用python matplotlib等数据可视化工具的方法。</p>
<a class="post-dummy-target" id="python-matplotlib"></a><h3>Python matplotlib</h3>
<a class="post-dummy-target" id="marplotlib的总体概念"></a><h4>marplotlib的总体概念</h4>
<p><figure><img src="/svg/loading.min.svg" data-sizes="auto" data-src="/images/anatomy.webp" alt="avatar" class="lazyload"><figcaption class="image-caption">avatar</figcaption></figure></p>
<p>最大的概念是figure，每个figure可以有多个axes，每个axes有两个或者三个（3D）axis，可以通过以下代码进行创建：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">fig</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">()</span> <span class="c1"># 创建一个figure</span>
<span class="n">fig</span><span class="p">,</span> <span class="n">ax</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">subplots</span><span class="p">()</span> <span class="c1"># 创建一个figure并返回figure和一个Axes</span>
<span class="n">fig</span><span class="p">,</span> <span class="n">axs</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">subplots</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># 创建一个带有2行2列（共4个）Axes的figure</span>
<span class="n">axs</span><span class="p">[</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">)</span>
<span class="n">axs</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">)</span>
<span class="o">......</span>
</code></pre></td></tr></table>
</div>
</div><p>subplots()返回Axes对象的数组，每个axes都是一个单独的子图，可以通过axes.Axes.set_xlim()和axes.Axes.set_ylim()方法控制x轴和y轴的长度，同时可以通过set_xlabel()和set_ylabel()来设置两个轴的标题，通过legend()方法显示该axes的图注。通过set_title()设置axes的大标题。注意，plot()函数的输入必须是numpy的array类型。</p>
<p>建议通过以下的格式来抽象出一个绘图函数：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">my_plotter</span><span class="p">(</span><span class="n">ax</span><span class="p">,</span> <span class="n">data1</span><span class="p">,</span> <span class="n">data2</span><span class="p">,</span> <span class="n">param_dict</span><span class="p">):</span>
    <span class="s2">&#34;&#34;&#34;
</span><span class="s2">    A helper function to make a graph
</span><span class="s2">    Parameters
</span><span class="s2">    -----------
</span><span class="s2">    ax : Axes
</span><span class="s2">    	The axes to draw to
</span><span class="s2">    data1 : array
</span><span class="s2">    	The x data
</span><span class="s2">    data2 : array
</span><span class="s2">    	The y data
</span><span class="s2">    param_dict : dict
</span><span class="s2">    	Dictionary of kwargs to pass to ax.plot
</span><span class="s2">    Returns
</span><span class="s2">    ------
</span><span class="s2">    out : list
</span><span class="s2">    	list of artists added
</span><span class="s2">    &#34;&#34;&#34;</span>
    <span class="n">out</span> <span class="o">=</span> <span class="n">ax</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">data1</span><span class="p">,</span><span class="n">data2</span><span class="p">,</span><span class="o">**</span><span class="n">param_dict</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">out</span>
</code></pre></td></tr></table>
</div>
</div><a class="post-dummy-target" id="plot函数的使用"></a><h4>plot函数的使用</h4>
<p>一般是：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="o">...</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>后面的参数有以下：</p>
<table>
<thead>
<tr>
<th>参数名</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>color</td>
<td>color颜色</td>
</tr>
<tr>
<td>linestyle</td>
<td>线形，{'-','&ndash;','-.',':'}</td>
</tr>
<tr>
<td>linewidth</td>
<td>线的宽度,float</td>
</tr>
<tr>
<td>marker</td>
<td>点的标记，具体见下</td>
</tr>
</tbody>
</table>
<p>可以通过format string控制，format string的格式为</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">fmt</span> <span class="o">=</span> <span class="s1">&#39;[marker][line][color]&#39;</span>
<span class="o">...</span>
<span class="n">fmt</span> <span class="o">=</span> <span class="s1">&#39;o-r&#39;</span>
<span class="n">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="n">fmt</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>点的标记有以下格式</p>
<table>
<thead>
<tr>
<th>character</th>
<th>description</th>
</tr>
</thead>
<tbody>
<tr>
<td>&lsquo;.&rsquo;</td>
<td>point marker</td>
</tr>
<tr>
<td>&lsquo;,&rsquo;</td>
<td>pixel marker</td>
</tr>
<tr>
<td>&lsquo;o&rsquo;</td>
<td>circle marker</td>
</tr>
<tr>
<td>&lsquo;v&rsquo;</td>
<td>triangle_down marker</td>
</tr>
<tr>
<td>&lsquo;^&rsquo;</td>
<td>triangle_up marker</td>
</tr>
<tr>
<td>&lsquo;&lt;&rsquo;</td>
<td>triangle_left marker</td>
</tr>
<tr>
<td>&lsquo;&gt;&rsquo;</td>
<td>triangle_right marker</td>
</tr>
<tr>
<td>&lsquo;1&rsquo;</td>
<td>tri_down marker</td>
</tr>
<tr>
<td>&lsquo;2&rsquo;</td>
<td>tri_up marker</td>
</tr>
<tr>
<td>&lsquo;3&rsquo;</td>
<td>tri_left marker</td>
</tr>
<tr>
<td>&lsquo;4&rsquo;</td>
<td>tri_right marker</td>
</tr>
<tr>
<td>&rsquo;s'</td>
<td>square marker</td>
</tr>
<tr>
<td>&lsquo;p&rsquo;</td>
<td>pentagon marker</td>
</tr>
<tr>
<td>&lsquo;*&rsquo;</td>
<td>star marker</td>
</tr>
<tr>
<td>&lsquo;h&rsquo;</td>
<td>hexagon1 marker</td>
</tr>
<tr>
<td>&lsquo;H&rsquo;</td>
<td>hexagon2 marker</td>
</tr>
<tr>
<td>&lsquo;+&rsquo;</td>
<td>plus marker</td>
</tr>
<tr>
<td>&lsquo;x&rsquo;</td>
<td>x marker</td>
</tr>
<tr>
<td>&lsquo;D&rsquo;</td>
<td>diamond marker</td>
</tr>
<tr>
<td>&rsquo;d'</td>
<td>thin_diamond marker</td>
</tr>
<tr>
<td>&lsquo;|&rsquo;</td>
<td>vline marker</td>
</tr>
<tr>
<td>&lsquo;-&rsquo;</td>
<td>hline marker</td>
</tr>
</tbody>
</table>
<p>颜色的分类有以下：</p>
<table>
<thead>
<tr>
<th>character</th>
<th>color</th>
</tr>
</thead>
<tbody>
<tr>
<td>&lsquo;b&rsquo;</td>
<td>blue</td>
</tr>
<tr>
<td>&lsquo;g&rsquo;</td>
<td>green</td>
</tr>
<tr>
<td>&lsquo;r&rsquo;</td>
<td>red</td>
</tr>
<tr>
<td>&lsquo;c&rsquo;</td>
<td>cyan</td>
</tr>
<tr>
<td>&rsquo;m'</td>
<td>magenta</td>
</tr>
<tr>
<td>&lsquo;y&rsquo;</td>
<td>yellow</td>
</tr>
<tr>
<td>&lsquo;k&rsquo;</td>
<td>black</td>
</tr>
<tr>
<td>&lsquo;w&rsquo;</td>
<td>white</td>
</tr>
</tbody>
</table>
<p>如果format string <em><strong>只设定了</strong></em> 颜色，可以使用16进制串如‘#008000’.</p>
<a class="post-dummy-target" id="分层设色地形图等高线图相关"></a><h4>分层设色地形图/等高线图相关</h4>
<a class="post-dummy-target" id="需要用到的函数"></a><h5>需要用到的函数</h5>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">contour</span><span class="p">([</span><span class="n">X</span><span class="p">,</span><span class="n">Y</span><span class="p">,]</span><span class="n">Z</span><span class="p">,[</span><span class="n">levels</span><span class="p">],</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> <span class="c1"># 只能绘制线</span>
<span class="n">contourf</span><span class="p">([</span><span class="n">X</span><span class="p">,</span><span class="n">Y</span><span class="p">,]</span><span class="n">Z</span><span class="p">,[</span><span class="n">levels</span><span class="p">],</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> <span class="c1"># 只能绘制色块</span>
</code></pre></td></tr></table>
</div>
</div><p>X,Y都是坐标，Z是高度，levels是高度的分级（必须是递增）重要参数有：</p>
<ul>
<li>colors : 指定每个level的颜色，如果是contour则指定了线的颜色，如果是contourf则指定了色块的颜色</li>
<li>extend : 取值有{&lsquo;neither&rsquo;, &lsquo;both&rsquo;, &lsquo;min&rsquo;, &lsquo;max&rsquo;}, 这个指定了超出等级范围的色块的显示，如果设置neither，超出范围都是空白，如果选min则对低于最低level的有效，如果选max则对高于最高level的有效，选both对所有范围都有效，一般选both。可以通过cmap的set_over()和set_under()来设定超过上限和下限的颜色，更换颜色以后需要使用cs.changed()来调整（注：cs是contour或者contourf的返回，是QuadContourSet类型，大概是代表了所有等高线的一个集合set）</li>
<li>linewidths: 线的宽度，只适用于contour</li>
<li>linestyles:线的类型，可选的值有{None, &lsquo;solid&rsquo;, &lsquo;dashed&rsquo;, &lsquo;dashdot&rsquo;, &lsquo;dotted&rsquo;}，只适用于contour</li>
<li>extend : 一个四元组如（-3,4,-4,3）,指定了图片的左上角和右下角，即划分了范围</li>
</ul>
<p>一个简单的例子如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span><span class="lnt">9
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">numpy</span> <span class="kn">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="kn">as</span> <span class="nn">plt</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">10</span><span class="p">)</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">)</span>

<span class="n">h</span> <span class="o">=</span> <span class="n">x</span> <span class="o">*</span> <span class="n">y</span>
<span class="n">cs</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">contourf</span><span class="p">(</span><span class="n">h</span><span class="p">,</span> <span class="n">levels</span><span class="o">=</span><span class="p">[</span><span class="mi">10</span><span class="p">,</span><span class="mi">30</span><span class="p">,</span><span class="mi">50</span><span class="p">],</span> 
	<span class="n">colors</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;#808080&#39;</span><span class="p">,</span><span class="s1">&#39;#A0A0A0&#39;</span><span class="p">,</span><span class="s1">&#39;#C0C0C0&#39;</span><span class="p">],</span><span class="n">extend</span><span class="o">=</span><span class="s1">&#39;both&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></td></tr></table>
</div>
</div><p>结果如下
<figure><img src="/svg/loading.min.svg" data-sizes="auto" data-src="/images/figure1.png" alt="图1" class="lazyload"><figcaption class="image-caption">图1</figcaption></figure></p>
<a class="post-dummy-target" id="在等高线上绘制值"></a><h5>在等高线上绘制值</h5>
<p>通过</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">clabel</span><span class="p">(</span><span class="n">CS</span><span class="p">,</span> <span class="n">inline</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">fontsize</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span> 
</code></pre></td></tr></table>
</div>
</div><p>绘制值，其中inline指定这个值是否被登高线遮住，一般是选择True，让值遮住线，fontsize则是选择值的字体大小。</p>
<p>例子如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">numpy</span> <span class="kn">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="kn">as</span> <span class="nn">plt</span>

<span class="n">delta</span> <span class="o">=</span> <span class="mf">0.025</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="o">-</span><span class="mf">3.0</span><span class="p">,</span> <span class="mf">3.0</span><span class="p">,</span> <span class="n">delta</span><span class="p">)</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="o">-</span><span class="mf">2.0</span><span class="p">,</span> <span class="mf">2.0</span><span class="p">,</span> <span class="n">delta</span><span class="p">)</span>
<span class="n">X</span><span class="p">,</span> <span class="n">Y</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">meshgrid</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">)</span>
<span class="n">Z1</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="o">-</span><span class="n">X</span><span class="o">**</span><span class="mi">2</span> <span class="o">-</span> <span class="n">Y</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
<span class="n">Z2</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="o">-</span><span class="p">(</span><span class="n">X</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span> <span class="o">-</span> <span class="p">(</span><span class="n">Y</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
<span class="n">Z</span> <span class="o">=</span> <span class="p">(</span><span class="n">Z1</span> <span class="o">-</span> <span class="n">Z2</span><span class="p">)</span> <span class="o">*</span> <span class="mi">2</span>
<span class="n">fig</span><span class="p">,</span> <span class="n">ax</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">subplots</span><span class="p">()</span>
<span class="n">CS</span> <span class="o">=</span> <span class="n">ax</span><span class="o">.</span><span class="n">contour</span><span class="p">(</span><span class="n">X</span><span class="p">,</span><span class="n">Y</span><span class="p">,</span><span class="n">Z</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">clabel</span><span class="p">(</span><span class="n">CS</span><span class="p">,</span> <span class="n">inline</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">fontsize</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span><span class="s1">&#39;Simplest default with labels&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></td></tr></table>
</div>
</div><p>结果如下</p>
<p><figure><img src="/svg/loading.min.svg" data-sizes="auto" data-src="/images/figure2.png" alt="图2" class="lazyload"><figcaption class="image-caption">图2</figcaption></figure></p>
<a class="post-dummy-target" id="绘制直方图"></a><h5>绘制直方图</h5>
<p>使用</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">hist</span><span class="p">()</span>
</code></pre></td></tr></table>
</div>
</div><p>进行绘制，主要的参数有</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>值</th>
</tr>
</thead>
<tbody>
<tr>
<td>x</td>
<td>输入，可以是一维或者多维数组（多维数组不要求等长）</td>
</tr>
<tr>
<td>bins</td>
<td>区间，一个一维数组如[1,2,3,4]，代表了1到2，2到3，3到4这三个区间，将会统计每个区间的个数并显示</td>
</tr>
<tr>
<td>histtype</td>
<td>绘制的柱的类型，可选的值有{&lsquo;bar&rsquo;,&lsquo;barstacked&rsquo;,&lsquo;step&rsquo;,&lsquo;stepfilled&rsquo;}，step指只画线</td>
</tr>
<tr>
<td>align</td>
<td>可选的值有{&lsquo;left&rsquo;, &lsquo;mid&rsquo;, &lsquo;right&rsquo;}，指柱子是在一个bin中的位置</td>
</tr>
<tr>
<td>orientation</td>
<td>可选的值有{&lsquo;vertical&rsquo;, &lsquo;horizontal&rsquo;}，指定了图的方向</td>
</tr>
<tr>
<td>stacked</td>
<td>多维数据的显示方式，正常是放在柱子的旁边，如果是True，将堆叠在上方</td>
</tr>
<tr>
<td>rwidth</td>
<td>柱子宽度，<strong>感觉</strong>是按（0，1）的百分比来的</td>
</tr>
</tbody>
</table>
<p>例子如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">numpy</span> <span class="kn">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="kn">as</span> <span class="nn">plt</span>

<span class="n">x</span> <span class="o">=</span> <span class="p">[[</span><span class="mf">1.2</span><span class="p">,</span><span class="mf">1.2</span><span class="p">,</span><span class="mf">2.2</span><span class="p">,</span><span class="o">-</span><span class="mf">2.2</span><span class="p">,</span><span class="o">-</span><span class="mf">1.2</span><span class="p">],[</span><span class="mf">2.2</span><span class="p">,</span><span class="o">-</span><span class="mf">0.2</span><span class="p">]]</span>   <span class="c1"># 一个二维的数据</span>
<span class="n">fig</span><span class="p">,</span> <span class="n">axs</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">subplots</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span>
<span class="n">axs</span><span class="p">[</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">hist</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">bins</span><span class="o">=</span><span class="p">[</span><span class="o">-</span><span class="mi">3</span><span class="p">,</span><span class="o">-</span><span class="mi">2</span><span class="p">,</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="n">rwidth</span><span class="o">=</span><span class="mf">0.5</span><span class="p">)</span>
<span class="n">axs</span><span class="p">[</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span><span class="s1">&#39;stacked=False&#39;</span><span class="p">)</span>

<span class="n">axs</span><span class="p">[</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">hist</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">bins</span><span class="o">=</span><span class="p">[</span><span class="o">-</span><span class="mi">3</span><span class="p">,</span><span class="o">-</span><span class="mi">2</span><span class="p">,</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="n">rwidth</span><span class="o">=</span><span class="mf">0.5</span><span class="p">,</span> <span class="n">stacked</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">axs</span><span class="p">[</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span><span class="s1">&#39;stacked=True&#39;</span><span class="p">)</span>

<span class="n">axs</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">hist</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">bins</span><span class="o">=</span><span class="p">[</span><span class="o">-</span><span class="mi">3</span><span class="p">,</span><span class="o">-</span><span class="mi">2</span><span class="p">,</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="n">rwidth</span><span class="o">=</span><span class="mf">0.5</span><span class="p">,</span> <span class="n">orientation</span><span class="o">=</span><span class="s1">&#39;horizontal&#39;</span><span class="p">)</span>
<span class="n">axs</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span><span class="s1">&#39;orientation=</span><span class="se">\&#39;</span><span class="s1">horizontal</span><span class="se">\&#39;</span><span class="s1">&#39;</span><span class="p">)</span>

<span class="n">axs</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">hist</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">bins</span><span class="o">=</span><span class="p">[</span><span class="o">-</span><span class="mi">3</span><span class="p">,</span><span class="o">-</span><span class="mi">2</span><span class="p">,</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="n">rwidth</span><span class="o">=</span><span class="mf">0.5</span><span class="p">,</span> <span class="n">histtype</span><span class="o">=</span><span class="s1">&#39;step&#39;</span><span class="p">)</span>
<span class="n">axs</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span><span class="s1">&#39;histtype=</span><span class="se">\&#39;</span><span class="s1">step</span><span class="se">\&#39;</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></td></tr></table>
</div>
</div><p>结果如下</p>
<p><figure><img src="/svg/loading.min.svg" data-sizes="auto" data-src="/images/figure3.png" alt="图3" class="lazyload"><figcaption class="image-caption">图3</figcaption></figure></p>
<a class="post-dummy-target" id="参考文献"></a><h3>参考文献</h3>
<ul>
<li><a href="https://matplotlib.org/tutorials/introductory/usage.html#sphx-glr-tutorials-introductory-usage-py" target="_blank">Matplotlib Usage Guide</a></li>
</ul>
</div><div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>本文于 2020-01-01 更新</span>
            </div>
            <div class="post-info-license"></div>
        </div>
        <div class="post-info-line">
            <div class="post-info-md"></div>
            <div class="post-info-share"><span><a href="//twitter.com/share?url=%2f2020%2f01%2fpython%25E5%258F%25AF%25E8%25A7%2586%25E5%258C%2596%2f&amp;text=Python%e5%8f%af%e8%a7%86%e5%8c%96&amp;via=xxxx" target="_blank" title="分享到 Twitter">
            <i class="fab fa-twitter fa-fw"></i>
        </a><a href="//www.facebook.com/sharer/sharer.php?u=%2f2020%2f01%2fpython%25E5%258F%25AF%25E8%25A7%2586%25E5%258C%2596%2f" target="_blank" title="分享到 Facebook">
            <i class="fab fa-facebook-square fa-fw"></i>
        </a><a href="//reddit.com/submit?url=%2f2020%2f01%2fpython%25E5%258F%25AF%25E8%25A7%2586%25E5%258C%2596%2f&amp;title=Python%e5%8f%af%e8%a7%86%e5%8c%96" target="_blank" title="分享到 Reddit">
            <i class="fab fa-reddit fa-fw"></i>
        </a><a href="//service.weibo.com/share/share.php?url=%2f2020%2f01%2fpython%25E5%258F%25AF%25E8%25A7%2586%25E5%258C%2596%2f&amp;appkey=&amp;title=Python%e5%8f%af%e8%a7%86%e5%8c%96" target="_blank" title="分享到 Weibo">
            <i class="fab fa-weibo fa-fw"></i>
        </a></span></div>
        </div>
    </div>

    <div class="post-info-more">
        <section><span class="tag">
                        <a href="/tags/python/"><i class="fas fa-tag fa-fw"></i>&nbsp;Python</a>&nbsp;
                    </span><span class="tag">
                        <a href="/tags/matplotlib/"><i class="fas fa-tag fa-fw"></i>&nbsp;matplotlib</a>&nbsp;
                    </span></section>
        <section>
            <span><a href="javascript:window.history.back();">返回</a></span>&nbsp;|&nbsp;<span><a href="/">主页</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/2020/01/%E7%BB%9F%E8%AE%A1%E5%AD%A6%E4%B9%A0%E6%96%B9%E6%B3%95/" class="prev" rel="prev" title="统计学习方法"><i class="fas fa-angle-left fa-fw"></i>统计学习方法</a>
            <a href="/2020/12/%E5%A4%87%E6%88%98%E7%BE%8E%E8%B5%9B/" class="next" rel="next" title="备战美赛">备战美赛<i class="fas fa-angle-right fa-fw"></i></a></div>
</div><div class="post-comment"></div>
    </article></div>
            </main><footer class="footer">
    <div class="copyright"><div class="copyright-line">由 <a href="https://gohugo.io/" target="_blank" rel="external nofollow noopener noreffer">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="external nofollow noopener noreffer">LoveIt<i class="far fa-heart fa-fw"></i></a>
        </div>

        <div class="copyright-line"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2020 - 2021</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/" target="_blank">ChenDong Zhu</a></span>&nbsp;|&nbsp;<span class="license"><a rel="license external nofollow noopener noreffer" href="https://creativecommons.org/licenses/by-nc/4.0/" target="_blank">CC BY-NC 4.0</a></span></div>
    </div>
</footer></div><a href="#" class="dynamic-to-top" id="dynamic-to-top" data-scroll>
            <span>&nbsp;</span>
        </a><script src="/js/lib/jquery/jquery.slim.min.js"></script><script src="/js/lib/lazysizes/lazysizes.min.js"></script><script src="/js/lib/smooth-scroll/smooth-scroll.polyfills.min.js"></script><script>window.scroll = new SmoothScroll('[data-scroll]', {speed: 300, speedAsDuration: true});</script><link rel="stylesheet" href="/css/lib/katex/katex.min.css"><script src="/js/lib/katex/katex.min.js"></script><script defer src="/js/lib/katex/auto-render.min.js"></script><link rel="stylesheet" href="/css/lib/katex/copy-tex.min.css"><script defer src="/js/lib/katex/copy-tex.min.js"></script><script defer src="/js/lib/katex/mhchem.min.js"></script><script>
        document.addEventListener("DOMContentLoaded", function () {
            renderMathInElement(document.body, {
                delimiters: [
                    { left: "$$", right: "$$", display: true },
                    { left: "\\(", right: "\\)", display: false },
                    { left: "\\[", right: "\\]", display: true },{ left: "$", right: "$", display: false },]
            });
        });
    </script>
    <script src="https://eqcn.ajz.miesnfu.com/wp-content/plugins/wp-3d-pony/live2dw/lib/L2Dwidget.min.js"></script>

    <script>
        L2Dwidget.init({
            
            "model": {
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                            
                jsonPath: "/data/Shinomiya_Kaguya/model.model.json",
                "scale": 1
            },
            
            "display": {
                "position": "left",
                "width": 150,
                "height": 300,
                "hOffset": 0,
                "vOffset": 0
            },
            "mobile": {
                "show": true,
                "scale": 0.5
            },
            "react": {
                "opacityDefault": 1,
                "opacityOnHover": 0.2
            }
        });
    </script><script src="/js/blog.min.js"></script></body>
</html>